package com.niiwoo.civet.account.service.local.openAccount2.order;

import com.niiwoo.civet.account.dao.entity.AccountBase;
import com.niiwoo.civet.account.dao.entity.GroupAccountCorrelateOrder;
import com.niiwoo.civet.account.dao.entity.OpenAccountRecord;
import com.niiwoo.civet.account.dao.mapper.GroupAccountCorrelateOrderMapperExt;
import com.niiwoo.civet.account.enums.AccountActiveEnum;
import com.niiwoo.civet.account.enums.GroupAccountCorrelateOrderStatusEnum;
import com.niiwoo.civet.account.enums.OpenAccountOrderStatusEnum;
import com.niiwoo.civet.account.enums.OpenAccountRecordStatusEnum;
import com.niiwoo.civet.account.service.local.AccountService;
import com.niiwoo.civet.account.service.local.openAccount2.dto.CreateRequest;
import com.niiwoo.civet.account.service.local.openAccount2.dto.OrderBasicInfo;
import com.niiwoo.civet.account.service.local.openAccount2.dto.UpdateRequest;
import com.niiwoo.civet.account.service.local.openAccount2.lanmao.LanMaoHelper;
import com.niiwoo.civet.account.service.local.openAccount2.type.GroupTypeable;
import com.niiwoo.tripod.lanmao.component.LanMaoGatewayService;
import com.niiwoo.tripod.lanmao.component.LanMaoSequence;
import com.niiwoo.tripod.lanmao.enums.GroupAccountCorrelateTypeEnum;
import com.niiwoo.tripod.lanmao.enums.UserAuthorizationEnum;
import com.niiwoo.tripod.lanmao.enums.UserRoleEnum;
import com.niiwoo.tripod.service.component.SnowflakeIdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Optional;
import java.util.Set;

@Component
public class GroupOrderHandler implements OpenAccountOrderOperation<GroupAccountCorrelateOrder>, GroupTypeable {

    @Autowired
    SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    LanMaoSequence lanMaoSequence;
    @Autowired
    AccountService accountService;
    @Autowired
    LanMaoGatewayService lanMaoGatewayService;
    @Autowired
    private GroupAccountCorrelateOrderMapperExt groupAccountCorrelateOrderMapperExt;

    @Override
    public boolean create(GroupAccountCorrelateOrder groupAccountCorrelateOrder) {
        return groupAccountCorrelateOrderMapperExt.insertSelective(groupAccountCorrelateOrder) > 0;
    }

    @Override
    public boolean update(GroupAccountCorrelateOrder groupAccountCorrelateOrder) {
        return groupAccountCorrelateOrderMapperExt.updateByPrimaryKeySelective(groupAccountCorrelateOrder) > 0;
    }

    @Override
    public GroupAccountCorrelateOrder getByRequestNo(String requestNo) {
        return groupAccountCorrelateOrderMapperExt.selectByRequestNo(requestNo);
    }

    @Override
    public boolean isSuccess(GroupAccountCorrelateOrder groupAccountCorrelateOrder) {
        return GroupAccountCorrelateOrderStatusEnum.except(groupAccountCorrelateOrder.getStatus(), GroupAccountCorrelateOrderStatusEnum.SUCCESS);
    }

    @Override
    public GroupAccountCorrelateOrder getNewOrder(CreateRequest request, OpenAccountRecord record) {
        // 是否待激活账户
        Optional<AccountBase> accountBaseOptional = Optional.ofNullable(accountService.getNiiwooAccount(record.getUserId(), UserRoleEnum.enumOf(record.getAccountRole())))
                .filter(b -> b.getImportUserActiva().equals(AccountActiveEnum.UNACTIVATED.getValue()));
        // 权限
        Set<String> authList = LanMaoHelper.getAuthSetByRole(request.getRole());
        accountBaseOptional.ifPresent(accountBase -> {
            if (accountBase.getTender().equals((byte) 1)) {
                authList.add(UserAuthorizationEnum.TENDER.name());
            }
            if (accountBase.getRepayment().equals((byte) 1)) {
                authList.add(UserAuthorizationEnum.REPAYMENT.name());
            }
            if (accountBase.getCreditAssignment().equals((byte) 1)) {
                authList.add(UserAuthorizationEnum.CREDIT_ASSIGNMENT.name());
            }
            if (accountBase.getCompensatory().equals((byte) 1)) {
                authList.add(UserAuthorizationEnum.COMPENSATORY.name());
            }
            if (accountBase.getWithdraw().equals((byte) 1)) {
                authList.add(UserAuthorizationEnum.WITHDRAW.name());
            }
            if (accountBase.getRecharge().equals((byte) 1)) {
                authList.add(UserAuthorizationEnum.RECHARGE.name());
            }
            // 如果是待激活账户，这里必须修改 record 的 accountNo
            record.setAccountNo(accountBase.getAccountNo());
        });
        GroupAccountCorrelateOrder order = new GroupAccountCorrelateOrder();
        order.setId(snowflakeIdWorker.nextId());
        order.setRequestNo(lanMaoSequence.getRequestNo());
        order.setAccountNo(record.getAccountNo());
        order.setUserId(record.getUserId());
        order.setGroupAccountNo(record.getGroupAccountNo());
        order.setUserRole(record.getAccountRole());
        if (accountBaseOptional.isPresent()) {
            order.setCorrelateType(GroupAccountCorrelateTypeEnum.ACTIVE_AUTH.getValue());
        } else {
            order.setCorrelateType(GroupAccountCorrelateTypeEnum.REGISTER_AUTH.getValue());
        }
        order.setAuthList(String.join(",", authList));
        order.setStatus(OpenAccountOrderStatusEnum.PROCESSING.getValue());
        order.setCreateTime(new Date());
        return order;
    }

    @Override
    public OrderBasicInfo getOrderBasicInfo(GroupAccountCorrelateOrder groupAccountCorrelateOrder) {
        OrderBasicInfo orderBasicInfo = new OrderBasicInfo();
        orderBasicInfo.setUserId(groupAccountCorrelateOrder.getUserId());
        orderBasicInfo.setRole(groupAccountCorrelateOrder.getUserRole());
        orderBasicInfo.setAccountNo(groupAccountCorrelateOrder.getAccountNo());
        orderBasicInfo.setAuthList(groupAccountCorrelateOrder.getAuthList());
        if (GroupAccountCorrelateTypeEnum.REGISTER_AUTH.getValue().equals(groupAccountCorrelateOrder.getCorrelateType())) {
            orderBasicInfo.setIsInitAccount(true);
        } else {
            orderBasicInfo.setIsInitAccount(false);
        }
        return orderBasicInfo;
    }

    @Override
    public GroupAccountCorrelateOrder getUpdateOrder(GroupAccountCorrelateOrder oldOrder, UpdateRequest request, OpenAccountRecordStatusEnum recordStatus) {
        GroupAccountCorrelateOrder updateOrder = new GroupAccountCorrelateOrder();
        updateOrder.setId(oldOrder.getId());
        switch (recordStatus) {
            // 开户成功
            case SUCCESS: {
                updateOrder.setStatus(GroupAccountCorrelateOrderStatusEnum.SUCCESS.getValue());
            }
            break;
            // 失败
            case EXPIRED:
            case FAILURE: {
                updateOrder.setStatus(GroupAccountCorrelateOrderStatusEnum.FAILURE.getValue());
            }
            break;
            // 默认不修改状态
            default:
                updateOrder.setStatus(oldOrder.getStatus());
        }
        updateOrder.setErrorCode(request.getErrorCode());
        updateOrder.setErrorMessage(request.getErrorMessage());
        return updateOrder;
    }


}
